<template>
  <el-row :class="prefixCls" :gutter="20" justify="space-between">
    <el-col :lg="12" :md="24" :sm="24" :xl="12" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="font-bold text-18px">充值排行榜</span>
            <el-radio-group v-model="rechargeDays" size="small" @change="getRechargeLank">
              <el-radio-button :label="7">7天</el-radio-button>
              <el-radio-button :label="30">30天</el-radio-button>
              <el-radio-button :label="90">90天</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <el-skeleton :loading="loading" :rows="5" animated>
          <template #default>
            <div class="rank-list">
              <div v-for="(item, index) in rechargeRankList" :key="item.userId" class="rank-item">
                <div class="rank-index" :class="{'rank-top': index === 0}">{{ index + 1 }}</div>
                <div class="rank-name">{{ item.userName }}</div>
                <div class="rank-amount">{{ formatAmount(item.totalAmount) }}</div>
                <div v-if="index === 0" class="rank-icon">🔥</div>
              </div>
              <div v-if="rechargeRankList.length === 0" class="no-data">暂无数据</div>
            </div>
          </template>
        </el-skeleton>
      </el-card>
    </el-col>

    <el-col :lg="12" :md="24" :sm="24" :xl="12" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="font-bold text-18px">消费排行榜</span>
            <el-radio-group v-model="consumeDays" size="small" @change="getConsumeLank">
              <el-radio-button :label="7">7天</el-radio-button>
              <el-radio-button :label="30">30天</el-radio-button>
              <el-radio-button :label="90">90天</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <el-skeleton :loading="loading" :rows="5" animated>
          <template #default>
            <div class="rank-list">
              <div v-for="(item, index) in consumeRankList" :key="item.userId" class="rank-item">
                <div class="rank-index" :class="{'rank-top': index === 0}">{{ index + 1 }}</div>
                <div class="rank-name">{{ item.userName }}</div>
                <div class="rank-amount">{{ formatAmount(item.totalAmount) }}</div>
                <div v-if="index === 0" class="rank-icon">🔥</div>
              </div>
              <div v-if="consumeRankList.length === 0" class="no-data">暂无数据</div>
            </div>
          </template>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
  <el-row :gutter="20" justify="space-between">
    <el-col :lg="10" :md="24" :sm="24" :xl="10" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" animated>
          <Echart :height="300" :options="pieOptionsData" />
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :lg="14" :md="24" :sm="24" :xl="14" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" animated>
          <Echart :height="300" :options="barOptionsData" />
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :span="24">
      <el-card class="mb-20px" shadow="hover">
        <el-skeleton :loading="loading" :rows="4" animated>
          <Echart :height="350" :options="lineOptionsData" />
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import {set} from 'lodash-es'
import {EChartsOption} from 'echarts'

import {useDesign} from '@/hooks/web/useDesign'
import {barOptions, lineOptions, pieOptions} from './echarts-data'
import {FinancialFlowApi, UserRank} from '@/api/javainfo/financialflow'

defineOptions({ name: 'Home2' })

const { t } = useI18n()
const loading = ref(true)
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('panel')
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption

// 充值排行榜数据
const rechargeRankList = ref<UserRank[]>([])
const rechargeDays = ref(7)

// 消费排行榜数据
const consumeRankList = ref<UserRank[]>([])
const consumeDays = ref(7)

// 格式化金额（分转元）
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '¥0.00'
  return '¥' + (amount / 100).toFixed(2)
}

// 获取充值排行榜数据
const getRechargeLank = async () => {
  try {
    const data = await FinancialFlowApi.getUserRank({
      days: rechargeDays.value,
      amountType: 'RECHARGE'
    })
    rechargeRankList.value = data || []
  } catch (error) {
    console.error('获取充值排行榜数据失败', error)
    rechargeRankList.value = []
  }
}

// 获取消费排行榜数据
const getConsumeLank = async () => {
  try {
    const data = await FinancialFlowApi.getUserRank({
      days: consumeDays.value,
      amountType: 'CONSUME'
    })
    consumeRankList.value = data || []
  } catch (error) {
    console.error('获取消费排行榜数据失败', error)
    consumeRankList.value = []
  }
}

// 用户来源
const getUserAccessSource = async () => {
  const data = [
    { value: 335, name: 'analysis.directAccess' },
    { value: 310, name: 'analysis.mailMarketing' },
    { value: 234, name: 'analysis.allianceAdvertising' },
    { value: 135, name: 'analysis.videoAdvertising' },
    { value: 1548, name: 'analysis.searchEngines' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  set(pieOptionsData, 'series.data', data)
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 13253, name: 'analysis.monday' },
    { value: 34235, name: 'analysis.tuesday' },
    { value: 26321, name: 'analysis.wednesday' },
    { value: 12340, name: 'analysis.thursday' },
    { value: 24643, name: 'analysis.friday' },
    { value: 1322, name: 'analysis.saturday' },
    { value: 1324, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption

// 每月销售总额
const getMonthlySales = async () => {
  const data = [
    { estimate: 100, actual: 120, name: 'analysis.january' },
    { estimate: 120, actual: 82, name: 'analysis.february' },
    { estimate: 161, actual: 91, name: 'analysis.march' },
    { estimate: 134, actual: 154, name: 'analysis.april' },
    { estimate: 105, actual: 162, name: 'analysis.may' },
    { estimate: 160, actual: 140, name: 'analysis.june' },
    { estimate: 165, actual: 145, name: 'analysis.july' },
    { estimate: 114, actual: 250, name: 'analysis.august' },
    { estimate: 163, actual: 134, name: 'analysis.september' },
    { estimate: 185, actual: 56, name: 'analysis.october' },
    { estimate: 118, actual: 99, name: 'analysis.november' },
    { estimate: 123, actual: 123, name: 'analysis.december' }
  ]
  set(
    lineOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(lineOptionsData, 'series', [
    {
      name: t('analysis.estimate'),
      smooth: true,
      type: 'line',
      data: data.map((v) => v.estimate),
      animationDuration: 2800,
      animationEasing: 'cubicInOut'
    },
    {
      name: t('analysis.actual'),
      smooth: true,
      type: 'line',
      itemStyle: {},
      data: data.map((v) => v.actual),
      animationDuration: 2800,
      animationEasing: 'quadraticOut'
    }
  ])
}

const getAllApi = async () => {
  await Promise.all([
    getRechargeLank(),
    getConsumeLank(),
    getUserAccessSource(),
    getWeeklyUserActivity(),
    getMonthlySales()
  ])
  loading.value = false
}

getAllApi()
</script>

<style lang="scss" scoped>
$prefix-cls: #{$namespace}-panel;

.#{$prefix-cls} {
  &__item {
    &--peoples {
      color: #40c9c6;
    }

    &--message {
      color: #36a3f7;
    }

    &--money {
      color: #f4516c;
    }

    &--shopping {
      color: #34bfa3;
    }

    &:hover {
      :deep(.#{$namespace}-icon) {
        color: #fff !important;
      }

      .#{$prefix-cls}__item--icon {
        transition: all 0.38s ease-out;
      }

      .#{$prefix-cls}__item--peoples {
        background: #40c9c6;
      }

      .#{$prefix-cls}__item--message {
        background: #36a3f7;
      }

      .#{$prefix-cls}__item--money {
        background: #f4516c;
      }

      .#{$prefix-cls}__item--shopping {
        background: #34bfa3;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rank-list {
  padding: 0 10px;
}

.rank-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.rank-index {
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #f0f0f0;
  border-radius: 50%;
  margin-right: 16px;
  font-weight: bold;
}

.rank-top {
  background-color: #f56c6c;
  color: white;
}

.rank-name {
  flex: 1;
  font-size: 14px;
}

.rank-amount {
  font-weight: bold;
  color: #f56c6c;
  margin-right: 8px;
}

.rank-icon {
  font-size: 20px;
  margin-left: 4px;
}

.no-data {
  text-align: center;
  padding: 20px 0;
  color: #909399;
}
</style>
